import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rtk/common/assets.dart';
import 'package:flutter_rtk/common/constants.dart';
import 'package:flutter_rtk/models/app_model.dart';
import 'package:flutter_rtk/models/user_info_model.dart';
import 'package:flutter_rtk/router/index.dart';
import 'package:flutter_rtk/service/store_service.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

class MinePage extends StatefulWidget {
  const MinePage({super.key});

  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  Widget _buildMainView() {
    return Scaffold(
      backgroundColor: const Color(0xFFF4F4F4),
      body: Stack(children: [
        // 背景
        _buildMineBg(),
        // 设置项目
        SafeArea(
          child: Column(children: [
            _buildMineAppbar(),
            _buildUserInfo(),
            _buildItems(),
            _buildExitButton(),
          ]),
        )
      ]),
    );
  }

  _buildExitButton() {
    return InkWell(
      onTap: () {
        showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30.r)),
              title: Container(
                width: double.infinity,
                height: 45.h,
                alignment: Alignment.center,
                child: Text("提示", style: TextStyle(fontSize: 34.sp, fontWeight: FontWeight.w500, color: const Color(0xFF333333))),
              ),
              content: Container(
                width: 500.w,
                height: 80.h,
                decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(30.r)),
                child: Container(
                  width: double.infinity,
                  height: double.infinity,
                  alignment: Alignment.center,
                  child: Text("确定退出吗？", style: TextStyle(fontSize: 32.sp, fontWeight: FontWeight.w500, color: const Color(0xFF333333))),
                ),
              ),
              actionsAlignment: MainAxisAlignment.spaceAround,
              actionsPadding: EdgeInsets.only(bottom: 50.h),
              actions: [
                _buildCustomButton(label: "取消", onPressed: () => Navigator.pop(context)),
                _buildCustomButton(
                  label: "确定",
                  isConfirm: true,
                  onPressed: () async {
                    // invoke server logout api
                    // await AppApi.logout();
                    await StoreService.to.remove(AppConstants.userIsLogin);
                    // 移除状态
                    context.read<AppModel>().resetCurrentIdx();
                    // ignore: use_build_context_synchronously
                    Navigator.of(context).pushNamedAndRemoveUntil(AppRouters.login, (router) => false);
                  },
                ),
              ],
            );
          },
        );
      },
      child: Container(
        width: double.infinity,
        height: 100.h,
        alignment: Alignment.center,
        margin: EdgeInsets.only(top: 25.h, left: 25.w, right: 25.w),
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(15.r)),
        child: Text(
          "退出",
          style: TextStyle(
            fontSize: 30.sp,
            fontWeight: FontWeight.w500,
            color: const Color(0xFFFF5858),
          ),
        ),
      ),
    );
  }

  _buildItems() {
    return Container(
      width: double.infinity,
      height: 400.h,
      // height: 400.h + 220.h,
      margin: EdgeInsets.symmetric(horizontal: 25.h),
      clipBehavior: Clip.antiAlias,
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(20.r)),
      child: Column(children: [
        _buildItem(
          label: "我的项目",
          prefixIcon: Image.asset(AppAssets.mineProject),
          onClick: () {},
          suffixIcon: Consumer<AppModel>(builder: (context, app, child) {
            if (app.currentProjectInfo == null) {
              return const SizedBox.shrink();
            }
            return Text(app.currentProjectInfo!.mergeName, style: TextStyle(fontWeight: FontWeight.normal, fontSize: 30.sp, color: const Color(0xFF333333)), overflow: TextOverflow.ellipsis);
          }),
        ),
        _buildItem(
          label: "绑定手机号",
          prefixIcon: Image.asset(AppAssets.minePhone),
          onClick: () => {},
          suffixIcon: Consumer<UserInfoModel>(builder: (context, user, child) {
            return Text(_handlePhone(user.userInfo.phone), style: TextStyle(fontWeight: FontWeight.normal, fontSize: 30.sp, color: const Color(0xFF333333)));
          }),
        ),
        _buildItem(
          label: "关于我们",
          prefixIcon: Image.asset(AppAssets.mineAboutUs),
          onClick: () => {},
          suffixIcon: Text("版权号: 1.0", style: TextStyle(fontWeight: FontWeight.normal, fontSize: 30.sp, color: const Color(0xFF333333))),
        ),
        _buildItem(
          label: "设置",
          prefixIcon: Image.asset(AppAssets.mineSetting),
          // hasUnderline: false,
          onClick: () => Navigator.pushNamed(context, AppRouters.toSettingPage),
        ),
        // _buildItem(
        //   label: "H5调试",
        //   prefixIcon: Image.asset(AppAssets.mineSetting),
        //   onClick: () async {
        //     // EasyLoading.showInfo("下载H5压缩包中...");
        //     var directory = await getApplicationDocumentsDirectory();
        //     String business = "RTK";
        //     // 加载数据
        //     // ignore: use_build_context_synchronously
        //     Navigator.pushNamed(context, AppRouters.webview, arguments: {"title": "H5调试", "url": "${directory.path}/html/$business/index.html?isLocal=1"});
        //   },
        // ),
        // _buildItem(
        //   label: "数据查看",
        //   prefixIcon: Image.asset(AppAssets.mineSetting),
        //   hasUnderline: false,
        //   onClick: () {
        //     Navigator.pushNamed(context, AppRouters.toSeeDataDemoPage);
        //   },
        // ),
      ]),
    );
  }

  _buildUserInfo() {
    return Container(
      width: double.infinity,
      height: 130.h,
      margin: EdgeInsets.only(left: 26.w, bottom: 25.h),
      child: Consumer<UserInfoModel>(builder: (context, user, child) {
        return Row(children: [
          Container(
            width: 130.h,
            height: 130.h,
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(130.h)),
            clipBehavior: Clip.antiAlias,
            child: user.userInfo.avatar.isNotEmpty ? CachedNetworkImage(imageUrl: user.userInfo.avatar, fit: BoxFit.fill) : Image.asset(AppAssets.defaultAvatar),
          ),
          SizedBox(width: 22.w),
          Expanded(
            child: Column(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [
              Text(user.userInfo.deptName, style: TextStyle(fontSize: 32.sp, color: Colors.white, fontWeight: FontWeight.w500)),
              SizedBox(height: 4.h),
              SizedBox(
                width: double.infinity,
                height: 42.h,
                child: Text("${user.userInfo.name} | ${user.userInfo.deptName}", style: TextStyle(fontSize: 30.sp, color: Colors.white, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
              ),
            ]),
          )
        ]);
      }),
    );
  }

  _buildMineAppbar() {
    return SizedBox(
      width: double.infinity,
      height: kToolbarHeight,
      child: Center(
        child: Text("我的", style: TextStyle(fontSize: 32.sp, color: Colors.white, fontWeight: FontWeight.w600)),
      ),
    );
  }

  _buildMineBg() {
    return Container(
      width: double.infinity,
      height: 390.h,
      decoration: const BoxDecoration(
        image: DecorationImage(image: AssetImage(AppAssets.mineBg), fit: BoxFit.fill),
      ),
    );
  }

  _buildCustomButton({required String label, required Function()? onPressed, bool isConfirm = false}) {
    return SizedBox(
      width: 190.w,
      height: 80.h,
      child: TextButton(
        style: ButtonStyle(
          splashFactory: NoSplash.splashFactory,
          backgroundColor: MaterialStateProperty.all(isConfirm ? AppConstants.brandColor : const Color(0xFFF5FAFF)),
          shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(90.r), side: isConfirm ? BorderSide.none : const BorderSide(color: AppConstants.brandColor))),
          padding: MaterialStateProperty.all(EdgeInsets.zero),
          elevation: MaterialStateProperty.all(0),
        ),
        onPressed: onPressed,
        child: Text(
          label,
          style: TextStyle(
            fontSize: 30.sp,
            color: isConfirm ? Colors.white : AppConstants.brandColor,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
    );
  }

  /// height: 120.h
  _buildItem({required Widget prefixIcon, required String label, required GestureTapCallback onClick, Widget? suffixIcon, bool hasUnderline = true}) {
    suffixIcon = suffixIcon ??
        Container(
          alignment: Alignment.centerRight,
          width: 18.w,
          height: 30.h,
          child: Image.asset(AppAssets.mineRightArrow),
        );
    return InkWell(
      onTap: onClick,
      child: Container(
        width: double.infinity,
        height: 100.h,
        margin: EdgeInsets.only(left: 50.w, right: 50.w),
        decoration: hasUnderline ? BoxDecoration(border: Border(bottom: BorderSide(width: 1.h, color: const Color(0xFFE3E3E3)))) : null,
        child: Row(children: [
          Flexible(
            child: Row(children: [
              Container(alignment: Alignment.centerRight, width: 48.w, height: 48.h, child: prefixIcon),
              SizedBox(width: 24.w),
              Text(label, style: TextStyle(fontSize: 30.sp, color: const Color(0xFF333333), fontWeight: FontWeight.normal)),
            ]),
          ),
          Container(alignment: Alignment.centerRight, width: 300.w, height: double.infinity, child: suffixIcon),
        ]),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return _buildMainView();
  }

  _handlePhone(String phone) {
    if (phone.length < 11) {
      return phone;
    }
    return "${phone.substring(0, 3)}****${phone.substring(7)}";
  }
}
